package ${packagePath}${rabbitmqPackage};

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import ${packagePath}constant.EosKanbanConstant;
import ${packagePath}service.data.KanbanDataService;
import ${packagePath}service.data.${entity}Service;
import ${packagePath}util.FastJsonUtil;
import ${packagePath}vo.data.${entity}VO;

import java.io.IOException;
import java.util.List;

/**
* rabbitmq异步处理
* ${introduce}
*
* @author ${author}
* @date ${date}
*/
@Slf4j
@Component
public class ${entity}Receiver {

    @Autowired
    private KanbanDataService kanbanDataService;

    @Autowired
    private ${entity}Service ${entity?uncap_first}Service;

    /**
     * 声明消费端 队列不存创建队列操作
     * @param data
     * @param deliveryTag
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "${entity?uncap_first}-queue", durable = "true"),
            exchange = @Exchange(value = "${entity?uncap_first}", type = "direct"), key = "init"), ackMode = "MANUAL")
    public void init(String data, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel)
            throws IOException {
        if (!StringUtils.isEmpty(data)) {
            // 将json转List
            List<${entity}VO> list = FastJsonUtil.json2List(data, ${entity}VO.class);
            // 获取用户登录信息 住户id
            String tenantId = list.get(0).getSpaceId();
            // 保存数据json格式到mysql
            kanbanDataService.saveByList(data, EosKanbanConstant.${entity?upper_case}DATA,tenantId);
            // 保存数据源
            ${entity?uncap_first}Service.saveData(list,tenantId);
            // 插入当前数据到ES json格式
            ${entity?uncap_first}Service.insertES("", EosKanbanConstant.${entity?upper_case}DATA,tenantId);
            // RabbitMQ的ack机制中，第二个参数返回true，表示需要将这条消息投递给其他的消费者重新消费
            channel.basicAck(deliveryTag, false);
        } else {
            // 第三个参数true，表示这个消息会重新进入队列
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
